import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { mockData } from '../utils/mockData';

const BusinessCategoryStats = () => {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const scrollIntervalRef = useRef(null);
  const startRef = useRef(0);
  const sortedCategoriesRef = useRef([]);
  const sortedDataRef = useRef([]);

  useEffect(() => {
    if (chartRef.current) {
      chartInstance.current = echarts.init(chartRef.current);
      updateChart();
      setupAutoScroll();
    }

    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
      if (scrollIntervalRef.current) {
        clearInterval(scrollIntervalRef.current);
      }
    };
  }, []);

  const updateChart = () => {
    const result = mockData.businessCategory;
    const categories = [];
    const data = [];

    result.forEach((item) => {
      categories.push(item.fis_category);
      data.push(parseInt(item.fis_category_work_order_count));
    });

    const sortedIndices = data
      .map((val, idx) => ({ val, idx }))
      .sort((a, b) => b.val - a.val)
      .map((item) => item.idx);

    sortedCategoriesRef.current = sortedIndices.map((idx) => categories[idx]);
    sortedDataRef.current = sortedIndices.map((idx) => data[idx]);

    const option = {
      tooltip: {
        trigger: "axis",
        backgroundColor: "rgba(6, 33, 68, 0.9)",
        borderColor: "#24bbec",
        textStyle: {
          color: "#fff",
          fontSize: 20,
        },
        formatter: function (params) {
          const data = params[0];
          return `${data.name}<br/>工单数量: <b>${data.value}</b>`;
        },
      },
      grid: {
        left: "3%",
        right: "5%",
        bottom: "5%",
        top: "20%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: sortedCategoriesRef.current,
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 16,
          rotate: 30,
          interval: 0,
          formatter: function (value) {
            return value.length > 8 ? value.substring(0, 8) + "..." : value;
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
        name: "业务类别",
        nameLocation: "end",
        nameTextStyle: {
          color: "#a2d3e8",
          fontSize: 16,
          padding: [10, 0, 0, 0],
        },
      },
      yAxis: {
        type: "value",
        name: "工单数量",
        nameTextStyle: {
          color: "#a2d3e8",
          fontSize: 16,
          padding: [0, 0, 20, 0],
        },
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 16,
        },
        splitLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.1)",
          },
        },
      },
      series: [
        {
          name: "工单数量",
          type: "line",
          data: sortedDataRef.current,
          smooth: true,
          symbol: "circle",
          symbolSize: 10,
          lineStyle: {
            width: 3,
            color: "#24bbec",
          },
          itemStyle: {
            color: "#24bbec",
            borderColor: "#fff",
            borderWidth: 2,
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(36, 187, 236, 0.5)" },
              { offset: 1, color: "rgba(36, 187, 236, 0.1)" },
            ]),
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: "rgba(36, 187, 236, 0.5)",
            },
            lineStyle: {
              width: 4,
              color: "#ffc640",
            }
          },
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
            color: "#fff",
            fontSize: 16,
            backgroundColor: "rgba(6, 33, 68, 0.7)",
            padding: [5, 8],
            borderRadius: 4,
          },
        },
      ],
      dataZoom: [
        {
          type: "inside",
          xAxisIndex: 0,
          zoomLock: false,
          minValueSpan: 10,
          maxValueSpan: 10,
          start: 0,
          end: 100,
        },
      ],
      animation: true,
      animationDuration: 1000,
      animationEasing: "cubicInOut",
    };

    if (chartInstance.current) {
      chartInstance.current.setOption(option);
    }
  };

  const setupAutoScroll = () => {
    const autoScroll = () => {
      if (sortedCategoriesRef.current.length === 0) return;

      const visibleItems = 10;
      startRef.current = (startRef.current + 1) % (sortedCategoriesRef.current.length - visibleItems + 1);
      
      if (chartInstance.current) {
        chartInstance.current.dispatchAction({
          type: "dataZoom",
          startValue: startRef.current,
          endValue: startRef.current + visibleItems,
          xAxisIndex: 0
        });
      }
    };

    scrollIntervalRef.current = setInterval(autoScroll, 5000);
  };

  return (
    <div className="business-category-container">
      <div 
        ref={chartRef} 
        id="business-category-chart"
      ></div>
    </div>
  );
};

export default BusinessCategoryStats;